<!--
 * @Descripttion: (报警记录表/cks_alarm_rec)
 * @Author: (admin)
 * @Date: (2025-7-23)
-->
<template>
  <div>
    <!-- 查询表单 -->
    <el-form style="margin-left: 5px;margin-top: 10px;" :model="queryParams" label-position="right" inline
      ref="queryRef" v-show="showSearch" @submit.prevent>
      <el-form-item :label="$t('produce.cksdevicerunrecordPage.page.productionLineCode')" prop="lineCode">
        <!-- <el-input v-model="queryParams.lineCode" @keyup.enter="handleQuery" :placeholder="$t('produce.cksdevicerunrecordPage.page.productionLineCodeInput')" clearable style="width: 230px" /> -->

        <el-select clearable style="width: 260px" v-model="queryParams.lineCode"
          @change="queryParams.stationCode = ''; state.options.workstationCodeOptions = state.options.productionLineList.find(item => item.lineCode === $event)?.workStation || []"
          :placeholder="$t('produce.cksdevicerunrecordPage.page.productionLineCodeInput')">
          <el-option v-for="item in options.productionLineOptions" :key="item.dictValue" :label="item.dictLabel"
            :value="item.dictValue" />
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('produce.cksdevicerunrecordPage.page.stationCode')" prop="stationCode">
        <!-- <el-input v-model="queryParams.stationCode" @keyup.enter="handleQuery" :placeholder="$t('produce.cksdevicerunrecordPage.page.stationCodeInput')" clearable style="width: 230px" /> -->
        <el-select clearable style="width: 260px" v-model="queryParams.stationCode"
          :placeholder="$t('produce.cksdevicerunrecordPage.page.stationCodeInput')">
          <el-option v-for="item in options.workstationCodeOptions" :key="item.WorkstationCode"
            :label="item.WorkstationCode" :value="item.WorkstationCode" />
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('produce.cksdevicerunrecordPage.page.dateRange')" prop="dateRange">
        <el-date-picker style="width: 360px" v-model="queryParams.dateRange" type="datetimerange"
          :default-time="defaultTime" :shortcuts="shortcuts" value-format="YYYY-MM-DD HH:mm:ss" range-separator="-" />
      </el-form-item>

      <el-form-item>
        <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具区域 -->
    <el-row :gutter="15" class="mb10">
      <el-col :span="1.5">
        <el-button type="primary" v-hasPermi="['cksdevicerunrec:add']" plain icon="plus" @click="handleAdd">
          {{ $t('btn.add') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" :disabled="single" v-hasPermi="['cksdevicerunrec:edit']" plain icon="edit"
          @click="handleUpdate">
          {{ $t('btn.edit') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" :disabled="multiple" v-hasPermi="['cksdevicerunrec:delete']" plain icon="delete"
          @click="handleDelete">
          {{ $t('btn.delete') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" v-hasPermi="['cksdevicerunrec:delete']" plain icon="delete" @click="handleClear">
          {{ $t('btn.clean') }}
        </el-button>
      </el-col>
      <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar> -->
    </el-row>

    <!-- 数据表格 -->
    <el-table :data="dataList" v-loading="loading" ref="table" border header-cell-class-name="el-table-header-cell"
      highlight-current-row @sort-change="sortChange" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column prop="id" label="Id" width="80"  align="center" v-if="columns.showColumn('id')" />
      <!-- <el-table-column prop="plcId" label="PLCID" align="center" v-if="columns.showColumn('plcId')" /> -->
      <el-table-column prop="productionLineCode" :label="$t('produce.cksdevicerunrecordPage.tableColumns.productionLineCode')" align="center" v-if="columns.showColumn('plcId')" />
      <el-table-column prop="stationCode" :label="$t('produce.cksdevicerunrecordPage.tableColumns.stationCode')" align="center" v-if="columns.showColumn('plcId')" />
      <el-table-column prop="dbBlock"  :label="$t('produce.cksdevicerunrecordPage.tableColumns.dbBlock')" align="center" v-if="columns.showColumn('dbBlock')" />
      <el-table-column prop="startTime" :label="$t('produce.cksdevicerunrecordPage.tableColumns.startTime')"  align="center" :show-overflow-tooltip="true"
        v-if="columns.showColumn('startTime')" />
      <el-table-column prop="endTime" :label="$t('produce.cksdevicerunrecordPage.tableColumns.endTime')"  align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('endTime')" />
      <el-table-column prop="duration" :label="$t('produce.cksdevicerunrecordPage.tableColumns.duration')"  align="center" v-if="columns.showColumn('duration')" />
      <el-table-column prop="effectType" :label="$t('produce.cksdevicerunrecordPage.tableColumns.effectType')"  align="center" v-if="columns.showColumn('effectType')">
        <template #default="scope">
          <dict-tag :options="options.effectTypeOptions" :value="scope.row.effectType" />
        </template>
      </el-table-column>
      <el-table-column prop="effectReason" :label="$t('produce.cksdevicerunrecordPage.tableColumns.effectReason')"  align="center" :show-overflow-tooltip="true"
        v-if="columns.showColumn('effectReason')" />
      <el-table-column prop="createTime" :label="$t('produce.cksdevicerunrecordPage.tableColumns.createTime')"  align="center"  :show-overflow-tooltip="true"
        v-if="columns.showColumn('createTime')" />
      <!-- <el-table-column prop="isDeleted" label="逻辑删除" align="center" v-if="columns.showColumn('isDeleted')">
        <template #default="scope">
          <dict-tag :options="options.isDeletedOptions" :value="scope.row.isDeleted" />
        </template>
      </el-table-column> -->
      <el-table-column :label="$t('btn.operate')"  align="center"  width="200">
        <template #default="scope">
          <el-button type="success" size="small" icon="edit"  v-hasPermi="['cksdevicerunrec:edit']"
            @click="handleUpdate(scope.row)">{{$t('btn.edit')}}</el-button>
          <el-button type="danger" size="small" icon="delete"  v-hasPermi="['cksdevicerunrec:delete']"
            @click="handleDelete(scope.row)">{{$t('btn.delete')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />


    <!-- 添加或修改设备运行记录对话框 -->
    <el-dialog :title="title" :lock-scroll="false" v-model="open">
      <el-form ref="formRef"  :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">

          <!-- <el-col :lg="12" v-if="opertype != 1">
            <el-form-item label="Id" prop="id">
              <el-input-number v-model.number="form.id" controls-position="right" placeholder="请输入Id"
                :disabled="true" />
            </el-form-item>
          </el-col> -->

          <el-col :lg="12">
            <el-form-item :label="$t('produce.cksdevicerunrecordPage.tableColumns.plcId')" prop="plcId">
              <el-input v-model.number="form.plcId" :placeholder="$t('produce.cksdevicerunrecordPage.formDialog.plcId')" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item :label="$t('produce.cksdevicerunrecordPage.tableColumns.dbBlock')" prop="dbBlock">
              <el-input v-model.number="form.dbBlock" :placeholder="$t('produce.cksdevicerunrecordPage.formDialog.dbBlock')" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item :label="$t('produce.cksdevicerunrecordPage.tableColumns.startTime')" prop="startTime">
              <el-date-picker v-model="form.startTime" type="datetime" :teleported="false"
                :placeholder="$t('produce.cksdevicerunrecordPage.formDialog.startTime')"></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item :label="$t('produce.cksdevicerunrecordPage.tableColumns.endTime')" prop="endTime">
              <el-date-picker v-model="form.endTime" type="datetime" :teleported="false"
                :placeholder="$t('produce.cksdevicerunrecordPage.formDialog.endTime')"></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item :label="$t('produce.cksdevicerunrecordPage.tableColumns.duration')" prop="duration">
              <el-input v-model.number="form.duration" :placeholder="$t('produce.cksdevicerunrecordPage.formDialog.duration')" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item :label="$t('produce.cksdevicerunrecordPage.tableColumns.effectType')" prop="effectType">
              <el-select v-model="form.effectType" :placeholder="$t('produce.cksdevicerunrecordPage.formDialog.effectType')">
                <el-option v-for="item in options.effectTypeOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- <el-col :lg="12">
            <el-form-item :label="$t('produce.cksdevicerunrecordPage.tableColumns.effectReason')" prop="effectReason">
              <el-input type="textarea" v-model="form.effectReason" :placeholder="$t('produce.cksdevicerunrecordPage.formDialog.effectReason')" />
            </el-form-item>
          </el-col> -->

          <el-col :lg="12">
            <el-form-item :label="$t('produce.cksdevicerunrecordPage.tableColumns.createTime')"  prop="createTime">
              <el-date-picker v-model="form.createTime" type="datetime" :teleported="false"
                :placeholder="$t('produce.cksdevicerunrecordPage.formDialog.createTime')"></el-date-picker>
            </el-form-item>
          </el-col>

          <!-- <el-col :lg="12">
            <el-form-item label="逻辑删除" prop="isDeleted">
              <el-radio-group v-model="form.isDeleted">
                <el-radio v-for="item in options.isDeletedOptions" :key="item.dictValue" :value="item.dictValue">
                  {{ item.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
          
        </el-row>
      </el-form>
      <template #footer v-if="opertype != 3">
        <el-button text @click="cancel">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="submitForm">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="cksdevicerunrecord">
import {
  listCksDeviceRunRecord,
  addCksDeviceRunRecord, delCksDeviceRunRecord,
  updateCksDeviceRunRecord, getCksDeviceRunRecord,
  clearCksDeviceRunRecord,
}
  from '@/api/business/cksdevicerunrecord.js'
import { queryProductionLinePlcInfo } from '@/api/business/plcconfig.js'
import dayjs from 'dayjs'

const { proxy } = getCurrentInstance()
const ids = ref([])
const loading = ref(false)
const showSearch = ref(true)
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])
const today = dayjs()

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  sort: '',
  sortType: 'asc',
  lineCode: '',
  stationCode: '',
  dateRange: [today.startOf('day').format('YYYY-MM-DD HH:mm:ss'), today.endOf('day').format('YYYY-MM-DD HH:mm:ss')],

})

// 时间范围快捷选项
const shortcuts = [
  {
    text: proxy.$t('common.today'),
    value: () => {
      const start = new Date().setHours(0, 0, 0, 0)
      const end = new Date().setHours(23, 59, 59, 999)
      return [start, end]
    },
  },
  {
    text: proxy.$t('common.thisWeek'),
    value: () => {
      const start = new Date()
      const end = new Date().setHours(23, 59, 59, 999)
      start.setHours(0, 0, 0, 0)
      start.setDate(start.getDate() - 7)
      return [start, end]
    },
  },
  {
    text: proxy.$t('common.thisMonth'),
    value: () => {
      const start = new Date()
      const end = new Date().setHours(23, 59, 59, 999)
      start.setHours(0, 0, 0, 0)
      start.setMonth(start.getMonth() - 1)
      return [start, end]
    },
  },
  {
    text: proxy.$t('common.last3Month'),
    value: () => {
      const start = new Date()
      const end = new Date().setHours(23, 59, 59, 999)
      start.setHours(0, 0, 0, 0)
      start.setMonth(start.getMonth() - 3)
      return [start, end]
    },
  },
]

const columns = ref([
  { visible: true, prop: 'id', label: 'Id' },
  { visible: true, prop: 'plcId', label: 'PLCID' },
  { visible: true, prop: 'dbBlock', label: '数据块' },
  { visible: true, prop: 'startTime', label: '开始时间' },
  { visible: true, prop: 'endTime', label: '结束时间' },
  { visible: true, prop: 'duration', label: '持续时间s' },
  { visible: true, prop: 'effectType', label: '影响类型' },
  { visible: false, prop: 'effectReason', label: '影响原因' },
  { visible: true, prop: 'createTime', label: '创建时间' },
  { visible: false, prop: 'isDeleted', label: '逻辑删除' },
])

const total = ref(0)
const dataList = ref([])
const queryRef = ref()
var dictParams = []

function getList() {
  loading.value = true
  const formBody = JSON.parse(JSON.stringify(queryParams));
  proxy.addDateRange(formBody, queryParams.dateRange);
  delete formBody.dateRange;
  listCksDeviceRunRecord(formBody).then(res => {
    const { code, data } = res
    if (code == 200) {
      dataList.value = data.result
      total.value = data.totalNum
      loading.value = false
    }
  })
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置查询操作
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1
  multiple.value = !selection.length;
}
// 自定义排序
function sortChange(column) {
  var sort = undefined
  var sortType = undefined

  if (column.prop != null && column.order != null) {
    sort = column.prop
    sortType = column.order

  }
  queryParams.sort = sort
  queryParams.sortType = sortType
  handleQuery()
}

/*************** form操作 ***************/
const formRef = ref()
const title = ref('')
// 操作类型 1、add 2、edit 3、view
const opertype = ref(0)
const open = ref(false)
const state = reactive({
  single: true,
  multiple: true,
  form: {},
  rules: {
    plcId: [{ required: true, message: proxy.$t('produce.cksdevicerunrecordPage.formDialogVerify.plcId'), trigger: "blur", type: "number" }],
    dbBlock: [{ required: true, message:  proxy.$t('produce.cksdevicerunrecordPage.formDialogVerify.dbBlock'), trigger: "blur", type: "number" }],
    startTime: [{ required: true, message:  proxy.$t('produce.cksdevicerunrecordPage.formDialogVerify.startTime'), trigger: "blur" }],
  },
  options: {
    // 影响类型 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
    effectTypeOptions: [
      { dictLabel: proxy.$t('produce.cksdevicerunrecordPage.effectType.type99'), dictValue: '99' }
    ],
  }
})

const { form, rules, options, single, multiple } = toRefs(state)

// 关闭dialog
function cancel() {
  open.value = false
  reset()
}

// 重置表单
function reset() {
  form.value = {
    id: null,
    plcId: null,
    dbBlock: null,
    startTime: null,
    endTime: null,
    duration: null,
    effectType: null,
    effectReason: null,
    createTime: null,
    isDeleted: null,
  };
  proxy.resetForm("formRef")
}


// 添加按钮操作
function handleAdd() {
  reset();
  open.value = true
  title.value = proxy.$t('produce.cksdevicerunrecordPage.formDialog.addTitle')
  opertype.value = 1
}
// 修改按钮操作
function handleUpdate(row) {
  reset()
  const id = row.id || ids.value
  getCksDeviceRunRecord(id).then((res) => {
    const { code, data } = res
    if (code == 200) {
      open.value = true
      title.value =  proxy.$t('produce.cksdevicerunrecordPage.formDialog.editTitle')
      opertype.value = 2
      data.effectType = data.effectType+"";
      form.value = {
        ...data,
      }
    }
  })
}

// 添加&修改 表单提交
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {

      if (form.value.id != undefined && opertype.value === 2) {
        updateCksDeviceRunRecord(form.value).then((res) => {
          proxy.$modal.msgSuccess(proxy.$t('common.operateSuccess'))
          open.value = false
          getList()
        })
      } else {
        addCksDeviceRunRecord(form.value).then((res) => {
          proxy.$modal.msgSuccess(proxy.$t('common.operateSuccess'))
          open.value = false
          getList()
        })
      }
    }
  })
}

// 删除按钮操作
function handleDelete(row) {
  const Ids = row.id || ids.value

  proxy
        .$confirm(proxy.$t("common.deleteConfirm", [Ids]), proxy.$t("common.systemTips"), {
            confirmButtonText: proxy.$t('common.ok'),
            cancelButtonText: proxy.$t('common.cancel'),
            type: "warning",
        })
    .then(function () {
      return delCksDeviceRunRecord(Ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess(proxy.$t('common.operateSuccess'))
    })
}

// 清空
function handleClear() {
  proxy
        .$confirm(proxy.$t("common.clearConfirm"), proxy.$t("common.systemTips"), {
            confirmButtonText: proxy.$t('common.ok'),
            cancelButtonText: proxy.$t('common.cancel'),
            type: "warning",
        })
    .then(function () {
      return clearCksDeviceRunRecord()
    })
    .then(() => {
      handleQuery()
      proxy.$modal.msgSuccess(proxy.$t('common.operateSuccess'))
    })
}


queryProductionLinePlcInfo().then(res => {
  const { code, data } = res
  if (code == 200) {
    state.options.productionLineList = data;
    state.options.productionLineOptions = data.map(item => ({
      dictLabel: item.lineCode,
      dictValue: item.lineCode
    }));
  }
})

handleQuery()
</script>